﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;

namespace LiveNet.Contacts
{
    public class TagCollection
    {
        #region Private Data
        private ArrayList tags = new ArrayList();
        #endregion

        #region Constructors
        internal TagCollection()
        {
        }

        internal TagCollection(XmlNode xmlnode)
        {
            FromXml(xmlnode);
        }
        #endregion

        #region Internal Methods
        internal void FromXml(XmlNode xmlnode)
        {
            if (xmlnode == null) return;

            XmlNodeList nodes = xmlnode.SelectNodes("Tag");
            if (nodes != null)
            {
                foreach (XmlNode node in nodes)
                {
                    Add(new Tag(node));
                }
            }
        }

        internal void Add(Tag tag)
        {
            tags.Add(tag);
        }

        internal void Remove(Tag tag)
        {
            tags.Remove(tag);
        }

        internal void RemoveAll()
        {
            tags.Clear();
        }
        #endregion

        #region Public Properties
        public int Count
        {
            get { return tags.Count; }
        }

        public object[] ToArray
        {
            get { return tags.ToArray(); }
        }

        public bool Changed
        {
            get
            {
                foreach (Tag tag in tags)
                {
                    if (tag.Changed) return true;
                }
                return false;
            }
            set
            {
                foreach (Tag tag in tags)
                {
                    tag.Changed = value;
                }
            }
        }
        #endregion

        #region Public Methods
        public XmlDocument ToXml(OperationType op)
        {
            XmlDocument xmldoc = new XmlDocument();
            string xml = "<Tags>";
            foreach (Tag tag in tags)
            {
                xml = xml + tag.ToXml(op).InnerXml;
            }
            xml = xml + "</Tags>";
            xmldoc.LoadXml(xml);

            return xmldoc;
        }

        public IEnumerator GetEnumerator()
        {
            return tags.GetEnumerator();
        }

        public Tag Find(Guid tagID)
        {
            foreach (Tag tag in tags)
            {
                if (tag.ID == tagID) return tag;
            }
            return null;
        }

        public Tag New()
        {
            return new Tag();
        }
        #endregion
    }
}
